#include "Game.h"

void Game::Init(const char* title, int width, int height, int bpp, bool fullscreen)
{
	m_running=true;
	TheEngine::Instance()->Init(EDT_DIRECT3D9,width,height,bpp,fullscreen,false,false,0);
	TheAudio::Instance()->Init();
	m_Title = title;
	m_lastFPS =-1;
}

void Game::Cleanup()
{	
	// cleanup all states
	while ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}
	TheEngine::Instance()->Cleanup();
	TheAudio::Instance()->Cleanup();
}

void Game::ChangeState(GameState* state) 
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

void Game::PushState(GameState* state)
{
	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

void Game::PopState()
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}
}

bool Game::HandleEvents(const SEvent& event) 
{
	// let the state handle events
	return states.back()->HandleEvents(event);
}

void Game::Update() 
{
	double newTime = TheEngine::Instance()->GetDevice()->getTimer()->getTime();
	m_dt = (newTime - m_lastTime)/1000;
	m_lastTime = newTime;
	// let the state update the game
	states.back()->Update();
}

void Game::Draw() 
{
	// let the state draw the screen
	states.back()->Draw();

	//get frames per second
	int fps = TheEngine::Instance()->GetVideo()->getFPS();

	if (m_lastFPS != fps)
	{
		core::stringw str = m_Title;
		str += TheEngine::Instance()->GetVideo()->getName();
		str += "] FPS:";
		str += fps;

		TheDevice->setWindowCaption(str.c_str());
		m_lastFPS = fps;
	}
}